package com.efounder.http.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.util.Log;

import com.efounder.email.adapter.DetailListAdapter.DownHandler;
import com.efounder.tbs.DisplayFileWithTbsUtil;
import com.efounder.util.GlobalMap;
import com.pansoft.resmanager.ResFileManager;
import com.utilcode.util.UriUtils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

/**
 * 邮件点击附件 下载并打开附件(总部邮箱)
 *
 * @author yqs
 */
@SuppressLint("DefaultLocale")
public class DownEmailAttachmentUtil {

    private String directory;
    private Context mcontext;
    private String urlStr;
    private String fileName;
    //private DownloaderTask task;
    private DownHandler downHandler;
    private Thread thread;
    private final String FRONTURL = "https://pgyd.zyof.com.cn/ESPWTN/servlet/DownLoad?url=";

    public DownEmailAttachmentUtil(Context mcontext, String urlStr, String fileName, DownHandler downHandler) {
        super();
        this.downHandler = downHandler;
        this.mcontext = mcontext;
        this.urlStr = urlStr;
        this.fileName = fileName;
        directory = ResFileManager.MEETING;
        File file = new File(directory);
        if (!file.exists() && !file.isDirectory()) {
            System.out.println("//不存在");
            file.mkdirs();
        } else {
            System.out.println("//目录存在");
        }


    }

    /**
     * 执行下载
     */
    public void taskStart() {
//		task = new DownloaderTask();
//		task.execute(urlStr);
        DPThread myThread = new DPThread(urlStr);
        thread = new Thread(myThread);
        thread.start();

    }

    public void taskEnd() {
//		if (task !=null) {
//			task.cancel(true);
//		}
        thread.interrupt();

    }

    /**
     * 国勘邮箱附件下载
     */
    public void taskGKStart(String emailId, String fileId,String gkurl) {
        thread = new GKThread(emailId, fileId,gkurl);
        thread.start();

    }

    public class DPThread extends Thread {
        String url;

        public DPThread(String urlStr) {
            this.url = urlStr;
        }

        ;

        @Override
        public void run() {
            // TODO Auto-generated method stub
            super.run();

            fileName = URLDecoder.decode(fileName);
            Log.i("tag", "fileName=" + fileName);

            // File directory=Environment.getExternalStorageDirectory();
            File file = new File(directory, fileName);
            if (file.exists()) {
                Log.i("tag", "The file has already exists.");
                openFile(fileName);
                return;
            }
            downHandler.sendEmptyMessage(0);
            try {
                String DPtokenId = GlobalMap.getProperty(
                        "DPEMAILTokenId", "");
                Log.i("DownEmailAttachmentUtil", "DPEmailTokenId:" + DPtokenId);
                url = URLEncoder.encode(url,
                        "GBK");
                DPtokenId = URLEncoder.encode(DPtokenId, "GBK");
                url = FRONTURL + url + "&cookie=" + DPtokenId;
                System.out.println("---dpurl--- :" + url);
                //创建按一个URL实例
                URL url1 = new URL(url);
                //创建一个HttpURLConnection的链接对象
                HttpURLConnection httpConn = (HttpURLConnection) url1.openConnection();


                Log.i("DownEmailAttachmentUtil", "url:" + url1.toString());
                httpConn.setRequestProperty("Cookie", DPtokenId);// 给服务器送登录后的cookie

                //获取所下载文件的InputStream对象
                InputStream input = httpConn.getInputStream();

                writeToSDCard(fileName, input);

                input.close();

                openFile(fileName);


            } catch (Exception e) {
                e.printStackTrace();
                openFile(null);
            }
        }

    }

    public class GKThread extends Thread {
        String emailId;
        String fileId;
        String gkUrl;

        public GKThread(String emailId, String fileId,String urlString) {
            this.emailId = emailId;
            this.fileId = fileId;
            this.gkUrl = urlString;
        }

        @Override
        public void run() {
            super.run();

            fileName = URLDecoder.decode(fileName);
            Log.i("tag", "fileName=" + fileName);
            File file = new File(directory, fileName);
            if (file.exists()) {
//                Log.i("tag", "The file has already exists.");
//                openFile(fileName);
//                return;
                file.delete();
            }
            downHandler.sendEmptyMessage(0);
            try {
                Class clazz = Class.forName("com.efounder.guokan.manager.CasLoginManager");
                Field field = clazz.getField("cookieStore");
                CookieStore cookieStore= (CookieStore) field.get(clazz);
                try {
                    emailId = URLEncoder.encode(emailId,"UTF-8");
                    fileId = URLEncoder.encode(fileId,"UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                String urlString = gkUrl
                        + emailId + "&fileId=" + fileId;
                DefaultHttpClient httpCient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(urlString);
                httpCient.setCookieStore(cookieStore);
                //第三步：执行请求，获取服务器发还的相应对象
                HttpResponse httpResponse = httpCient.execute(httpGet);
                //第四步：检查相应的状态是否正常：检查状态码的值是200表示正常
                // if (httpResponse.getStatusLine().getStatusCode() == 200) {
                //第五步：从相应对象当中取出数据，放到entity当中
                HttpEntity entity = httpResponse.getEntity();
                //  String response = EntityUtils.toString(entity, "utf-8");//将entity当中的数据转换为字符串
                InputStream input = entity.getContent();

                //  }

                writeToSDCard(fileName, input);

                input.close();

                openFile(fileName);


            } catch (Exception e) {
                e.printStackTrace();
                openFile(null);
            }
        }

    }


    public Intent getFileIntent(File file) {
        //       Uri uri = Uri.parse("http://m.ql18.com.cn/hpf10/1.pdf");
        Uri uri = UriUtils.getUriForFile(file);
        String type = getMIMEType(file);
        Log.i("tag", "type=" + type);
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, type);
        return intent;
    }

    public void writeToSDCard(String fileName, InputStream input) {

        //   if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
        // File directory=Environment.getExternalStorageDirectory();
        File file = new File(directory, fileName);
        //          if(file.exists()){
        //              Log.i("tag", "The file has already exists.");
        //              return;
        //          }
        try {
            FileOutputStream fos = new FileOutputStream(file);
            byte[] b = new byte[2048];
            int j = 0;
            while ((j = input.read(b)) != -1) {
                fos.write(b, 0, j);
            }
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
            /* }else{
                 Log.i("tag", "NO SDCard.");
	         }*/
    }

    private String getMIMEType(File f) {
        String type = "";
        String fName = f.getName();
           /* 取得扩展名 */
        String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();
	          
	       /* 依扩展名的类型决定MimeType */
        if (end.equals("pdf")) {
            type = "application/pdf";//
        } else if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") ||
                end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            type = "audio/*";
        } else if (end.equals("3gp") || end.equals("mp4")) {
            type = "video/*";
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png") ||
                end.equals("jpeg") || end.equals("bmp")) {
            type = "image/*";
        } else if (end.equals("apk")) {
	         /* android.permission.INSTALL_PACKAGES */
            type = "application/vnd.android.package-archive";
        } else if (end.equals("pptx") || end.equals("ppt")) {
            type = "application/vnd.ms-powerpoint";
        } else if (end.equals("docx") || end.equals("doc")) {
            type = "application/msword";
        } else if (end.equals("xlsx") || end.equals("xls")) {
            type = "application/vnd.ms-excel";
        } else {
            //        /*如果无法直接打开，就跳出软件列表给用户选择 */
            type = "*/*";
        }
        return type;
    }

    /**
     * 判断Intent 是否存在 防止崩溃
     *
     * @param context
     * @param intent
     * @return
     */
    private boolean isIntentAvailable(Context context, Intent intent) {
        final PackageManager packageManager = context.getPackageManager();
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
                PackageManager.GET_ACTIVITIES);
        return list.size() > 0;
    }

    public void openFile(String fileName) {
        downHandler.sendEmptyMessage(1);
        if (fileName == null) {
            downHandler.sendEmptyMessage(2);

            return;
        }
        downHandler.sendEmptyMessage(3);

        File file = new File(directory, fileName);
        Log.i("tag", "Path=" + file.getAbsolutePath());

        try {


            if (DisplayFileWithTbsUtil.displayFile(mcontext, file.getAbsolutePath())) {
                return;
            }
            Intent intent = getFileIntent(file);
            if (isIntentAvailable(mcontext, intent)) {
                mcontext.startActivity(intent);
            } else {
                downHandler.sendEmptyMessage(4);

            }
        } catch (Exception e) {
            downHandler.sendEmptyMessage(5);

        }
    }
}
